import io
import os
import requests
from PyQt5.QtWidgets import (QVBoxLayout, QPushButton, QLabel, QSpinBox,
                            QGroupBox, QFileDialog, QLineEdit, QFormLayout,
                            QMessageBox, QTreeWidget, QTreeWidgetItem, QWidget,
                            QHBoxLayout, QApplication)
from flask import send_file
from style_manager import StyleManager  # 添加到文件顶部


class NovelSplitterView(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.parent = parent
        self.init_ui()
        self.apply_theme()  # 初始化时应用主题

    def apply_theme(self):
        """应用当前主题样式"""
        if not hasattr(self.parent, 'current_theme'):
            return

        # 获取当前主题信息
        current_theme = self.parent.current_theme
        theme = StyleManager.get_theme(current_theme)
        text_color = theme['text']

        # 调试输出
        # print(f"当前主题: {current_theme}")
        # print(f"文字颜色: {text_color}")
        # print(f"实际应用到file_label的样式表: \n"
        #       f"QLabel#file_label {{ color: {text_color} !important; }}")

        # 强制设置file_label样式
        if hasattr(self, 'file_label'):
            # 先清除现有样式
            self.file_label.setStyleSheet("")

            # 设置最小化样式表确保优先级
            self.file_label.setStyleSheet(
                f"QLabel#file_label {{ color: {text_color} !important; }}"
            )

            # 强制刷新
            self.file_label.style().unpolish(self.file_label)
            self.file_label.style().polish(self.file_label)
            self.file_label.update()

        # 设置主窗口样式
        self.setStyleSheet(StyleManager.get_style("main_window", self.parent.current_theme))

        # 设置特殊组件样式
        if hasattr(self, 'upload_group'):
            self.upload_group.setStyleSheet(
                StyleManager.get_style("upload_group", self.parent.current_theme)
            )
            self.upload_group.update()

        # 设置树形控件样式
        if hasattr(self, 'result_tree'):
            self.result_tree.setStyleSheet("")
            self.result_tree.setStyleSheet(
                StyleManager.get_style("table", self.parent.current_theme)
            )
            self.result_tree.style().unpolish(self.result_tree)
            self.result_tree.style().polish(self.result_tree)
            self.result_tree.update()

        # 强制刷新整个窗口
        self.update()

        # 强制设置输入组件样式
        if hasattr(self, 'length_spin') and hasattr(self, 'prefix_edit'):
            input_style = StyleManager.get_style("input_fields", self.parent.current_theme)

            self.length_spin.setStyleSheet("")
            self.prefix_edit.setStyleSheet("")

            self.length_spin.setStyleSheet(input_style)
            self.prefix_edit.setStyleSheet(input_style)

            self.length_spin.style().unpolish(self.length_spin)
            self.length_spin.style().polish(self.length_spin)
            self.prefix_edit.style().unpolish(self.prefix_edit)
            self.prefix_edit.style().polish(self.prefix_edit)

            self.length_spin.update()
            self.prefix_edit.update()

    def init_ui(self):
        """初始化分集器UI"""
        layout = QVBoxLayout(self)
        layout.setContentsMargins(20, 20, 20, 20)
        layout.setSpacing(15)

        # 文件上传区域（不再使用QGroupBox）
        upload_layout = QVBoxLayout()

        # 文件选择按钮
        self.file_btn = QPushButton("选择TXT文件")
        self.file_btn.clicked.connect(self.select_file)
        self.file_btn.setStyleSheet(
            StyleManager.get_style("button", self.parent.current_theme)
        )
        upload_layout.addWidget(self.file_btn)

        # 文件信息显示
        self.file_label = QLabel("未选择文件")
        self.file_label.setObjectName("file_label")
        self.file_label.setStyleSheet(
            StyleManager.get_style("label", self.parent.current_theme)
        )
        upload_layout.addWidget(self.file_label)

        # 分章设置区域（不再使用QGroupBox）
        settings_layout = QFormLayout()

        # 目标字数
        self.length_spin = QSpinBox()
        self.length_spin.setRange(500, 10000)
        self.length_spin.setValue(3000)

        # 章节前缀
        self.prefix_edit = QLineEdit("######")

        # 设置统一样式
        input_style = StyleManager.get_style("input_fields", self.parent.current_theme)
        self.length_spin.setStyleSheet(input_style)
        self.prefix_edit.setStyleSheet(input_style)

        settings_layout.addRow("每章目标字数:", self.length_spin)
        settings_layout.addRow("章节标题前缀:", self.prefix_edit)

        # 操作按钮
        btn_layout = QHBoxLayout()
        self.process_btn = QPushButton("开始分章")
        self.process_btn.clicked.connect(self.process_file)
        btn_layout.addWidget(self.process_btn)

        self.reset_btn = QPushButton("重置")
        self.reset_btn.clicked.connect(self.reset)
        btn_layout.addWidget(self.reset_btn)

        settings_layout.addRow(btn_layout)

        # 结果区域
        self.result_tree = QTreeWidget()
        self.result_tree.setHeaderLabels(["章节标题", "字数"])
        self.result_tree.setColumnCount(2)

        # 动态设置列宽（百分比）
        def resize_columns():
            total_width = self.result_tree.width()
            self.result_tree.setColumnWidth(0, int(total_width * 0.9))
            self.result_tree.setColumnWidth(1, int(total_width * 0.1))

        # 初始设置
        resize_columns()

        # 更安全的事件绑定方式
        self.result_tree.resizeEvent = self._handle_resize_event

        # 操作按钮区域
        self.result_btn_layout = QHBoxLayout()
        self.expand_btn = QPushButton("全部展开")
        self.expand_btn.clicked.connect(self.result_tree.expandAll)
        self.collapse_btn = QPushButton("全部折叠")
        self.collapse_btn.clicked.connect(self.result_tree.collapseAll)
        self.copy_btn = QPushButton("复制当前章节")
        self.copy_btn.clicked.connect(self.copy_selected_chapter)
        self.mark_btn = QPushButton("转画本")
        self.mark_btn.clicked.connect(self.save_mark)

        self.result_btn_layout.addWidget(self.expand_btn)
        self.result_btn_layout.addWidget(self.collapse_btn)
        self.result_btn_layout.addWidget(self.copy_btn)
        self.result_btn_layout.addWidget(self.mark_btn)
        self.result_btn_layout.addStretch()

        # 组装布局
        layout.addLayout(upload_layout)
        layout.addLayout(settings_layout)
        layout.addLayout(self.result_btn_layout)
        layout.addWidget(self.result_tree, stretch=1)

    def _handle_resize_event(self, event):
        """处理resize事件的更安全方式"""
        total_width = self.result_tree.width()
        self.result_tree.setColumnWidth(0, int(total_width * 0.9))
        self.result_tree.setColumnWidth(1, int(total_width * 0.1))
        QTreeWidget.resizeEvent(self.result_tree, event)

    def select_file(self):
        """选择文件"""
        file_path, _ = QFileDialog.getOpenFileName(self, "选择TXT文件", "", "Text Files (*.txt)")
        if file_path:
            self.file_path = file_path
            self.file_label.setText(os.path.basename(file_path))

    def process_file(self):
        """处理文件分章"""
        if not hasattr(self, 'file_path'):
            QMessageBox.warning(self, "警告", "请先选择TXT文件")
            return

        try:
            # 读取文件内容
            with open(self.file_path, 'r', encoding='utf-8') as f:
                content = f.read()

            # 准备API请求
            api_url = "http://127.0.0.1:5000/resplit"
            files = {'file': open(self.file_path, 'rb')}
            data = {
                'targetLength': self.length_spin.value(),
                'chapterPrefix': self.prefix_edit.text()
            }

            # 发送请求
            response = requests.post(api_url, files=files, data=data)

            if response.status_code != 200:
                raise Exception(f"API返回错误: {response.text}")

            chapters = response.json()

            if not isinstance(chapters, list):
                raise Exception("API返回数据格式无效")

            # 显示结果
            self.show_results(chapters)

            # 显示成功消息
            QMessageBox.information(self, "成功", f"成功分章！共 {len(chapters)} 章")

        except requests.exceptions.RequestException as e:
            QMessageBox.critical(self, "网络错误", f"请求失败: {str(e)}")
        except Exception as e:
            QMessageBox.critical(self, "错误", f"处理文件失败: {str(e)}")
        finally:
            if 'files' in locals():
                files['file'].close()

    def show_results(self, chapters):
        """显示分章结果"""
        self.result_tree.clear()

        # 获取当前主题的文字颜色
        text_color = StyleManager.get_theme(self.parent.current_theme)['text']

        for chapter in chapters:
            item = QTreeWidgetItem(self.result_tree)

            # 为章节标题使用QLabel
            title_label = QLabel(chapter['title'])
            title_label.setStyleSheet(f"color: {text_color};")
            self.result_tree.setItemWidget(item, 0, title_label)

            # 为字数使用QLabel
            length_label = QLabel(str(chapter['length']) + "字")
            length_label.setStyleSheet(f"color: {text_color};")
            self.result_tree.setItemWidget(item, 1, length_label)

            # 添加章节内容作为子项
            content_item = QTreeWidgetItem(item)
            content_label = QLabel(chapter['content'])
            content_label.setStyleSheet(f"color: {text_color};")
            self.result_tree.setItemWidget(content_item, 0, content_label)

        # 默认展开所有章节
        self.result_tree.expandAll()

    def copy_selected_chapter(self):
        """复制当前选中的章节内容"""
        selected = self.result_tree.currentItem()
        if selected and selected.childCount() > 0:
            content = selected.child(0).text(0)
            clipboard = QApplication.clipboard()
            clipboard.setText(content)
            QMessageBox.information(self, "成功", "章节内容已复制到剪贴板")
        else:
            QMessageBox.warning(self, "警告", "请先选择一个章节")

    def reset(self):
        """重置状态"""
        if hasattr(self, 'file_path'):
            del self.file_path
        self.file_label.setText("未选择文件")
        self.length_spin.setValue(3000)
        self.prefix_edit.setText("######")
        self.result_tree.clear()

    def save_mark(self):
        """调用API接口实现转画本功能"""
        if not hasattr(self, 'file_path'):
            return {"error": "没有可用的文件"}, 400

        try:
            # 准备API请求
            api_url = "http://127.0.0.1:5000/saveMark"
            files = {'file': open(self.file_path, 'rb')}
            data = {
                'targetLength': self.length_spin.value(),
                'chapterPrefix': self.prefix_edit.text()
            }

            # 发送请求
            response = requests.post(api_url, files=files, data=data)

            if response.status_code != 200:
                raise Exception(f"API返回错误: {response.text}")

            # 返回文件下载响应
            return send_file(
                io.BytesIO(response.content),
                mimetype='application/zip',
                as_attachment=True,
                download_name='分章结果.zip'
            )

        except requests.exceptions.RequestException as e:
            return {"error": f"请求失败: {str(e)}"}, 500
        except Exception as e:
            return {"error": f"处理失败: {str(e)}"}, 500
        finally:
            if 'files' in locals():
                files['file'].close()